<template>
  <van-button :class="border ? '' : 'noBorder'" @click="getValidCode" v-bind="$attrs">{{ validText }}</van-button>
</template>

<script>
import { login_getSmsCode } from '@api/user.js';
import { Button, Toast } from 'vant';
export default {
  props: {
    phone: {
      Type: String,
      default: ''
    },
    border: {
      Type: Boolean,
      default: true
    }
  },
  components: {
    'van-button': Button
  },
  data() {
    return {
      timer: null,
      validText: '获取验证码'
    };
  },
  methods: {
    async getValidCode() {
      let { validText, phone } = this;
      if (validText === '获取验证码' || validText === '重新发送') {
        if (!this.phone) {
          return Toast('请输入手机号');
        } else if (!/^1[3456789]\d{9}$/.test(this.phone)) {
          return Toast('请输入正确的手机号');
        }
        let data = await login_getSmsCode({ phone });
        if (data.code === 200) {
          Toast('发送成功，请查收');
          this.validText = '60s';
          this.timer = window.setInterval(() => {
            if (this.validText.split('s')[0] === '1') {
              window.clearInterval(this.timer); //停止计时器
              this.validText = '重新发送';
            } else {
              this.validText = this.validText.split('s')[0] - 1 + 's';
            }
          }, 1000);
        } else {
          Toast(data.msg);
        }
      }
    }
  },
  beforeDestroy() {
    window.clearInterval(this.timer);
  }
};
</script>
<style lang="scss" scoped>
.noBorder {
  border: none;
}
</style>
